<script type="text/javascript">
var prestasi_edit;
var prestasi_delete;
$(document).ready(function(){
/* Start Variable Declaration */
    var prestasi_source;
    var prestasi_adapter;
    var prestasi_buttonAdd;
    var prestasi_searchField;
    var prestasi_expander=$('#prestasi_expander');
    var prestasi_save=$("#prestasi_save");
    var prestasi_reset=$("#prestasi_reset");
    
    var prestasi_grid=$('#prestasi_grid');

/* Form Component Declaration */
	$('.inputfield').jqxInput({ theme : global_theme });
    prestasi_expander.jqxExpander({width: '100%', theme : global_theme, toggleMode : 'none', expanded : false});
	$("#prestasi_lomba_id").jqxComboBox({
        width: 200,
        height: 25,
        displayMember: "lomba_judul",
        valueMember: "lomba_id",
        source: new $.jqx.dataAdapter({
            datatype: "json",
            root : 'results',
            datafields: [
                { name: 'lomba_id' },
                { name: 'lomba_judul' }
            ],
            url: "index.php/c_lomba/get_list"
        }),
		autoDropDownHeight : true
    });
	$("#prestasi_lomba_id").on('select', function(e){
		prestasi_juara_source['data']['lomba_id'] = $(this).jqxComboBox('val');
		prestasi_juara_adapter.dataBind();
	});
	var prestasi_juara_source = {
		datatype: "json",
		root : 'results',
		data : {lomba_id : 0},
		datafields: [
			{ name: 'juara_id' },
			{ name: 'juara_nama' },
			{ name: 'skor_id' },
			{ name: 'skor_angka' },
			{ name: 'juara_ket' }
		],
		url: "index.php/c_prestasi/get_list_juara_poin"
	};
	var prestasi_juara_adapter = new $.jqx.dataAdapter(prestasi_juara_source);
	$("#prestasi_juara_id").jqxComboBox({
        width: 200,
        height: 25,
        displayMember: "juara_ket",
        valueMember: "juara_id",
        source: prestasi_juara_adapter,
		autoDropDownHeight : true
    });
	$("#prestasi_tanggal").jqxDateTimeInput({ width: '200px', height: '25px', formatString : 'dd-MM-yyyy'});
    
    prestasi_save.jqxButton();
    prestasi_save.bind('click', function(e){ prestasi_save_form(e); });
    prestasi_reset.jqxButton();
    prestasi_reset.bind('click', function(e){ e.preventDefault(); prestasi_reset_form() });
    
/* Grid And Toolbar Declaration */
    prestasi_buttonAdd = $("<button style='margin-left: 5px;'><img src='assets/images/icons/add.png'> Tambah Data</button>");
    prestasi_buttonAdd.jqxButton({ width : 120 });
    prestasi_buttonAdd.bind('click', function(){ prestasi_expander.jqxExpander('expand'); });
    prestasi_searchField = $('<input type="text" class="inputfield" name="prestasi_search" placeholder="Pencarian">');
    prestasi_searchField.jqxInput({ theme : global_theme });

    prestasi_source={
        id : 'prestasi_id',
        url : 'index.php/c_prestasi/get_list',
        datatype : 'json',
        root : 'results',
		data : {search_text : ''},
        datafields : [
            { name : 'prestasi_id' },
            { name : 'prestasi_lomba_id' },
            { name : 'prestasi_sekolah_id' },
            { name : 'prestasi_tanggal' },
            { name : 'prestasi_juara_id' },
            { name : 'prestasi_skor' },
			{ name : 'prestasi_sekolah_nama' },
			{ name : 'juara_nama' },
			{ name : 'lomba_judul' }
        ],
		addrow: function (rowid, rowdata, position, commit) {
			commit(true);
		},
        beforeprocessing : function(data){
            prestasi_source.totalrecords = data[0].total;
        }
    }
    prestasi_adapter = new $.jqx.dataAdapter(prestasi_source);
   
    prestasi_grid.jqxGrid({
        source : prestasi_adapter,
        width : '100%',
        theme : global_theme,
        pagesize : 15,
        pagesizeoptions : [15],
        sortable : true,
		pageable: true,
        filterable : true,
        columnsresize : true,
        autoheight : true,
        virtualmode : true,
        showtoolbar: true,
        rendertoolbar: function (toolbar) {
            var me = this;
            var container = $("<div style='margin: 5px;'></div>");
			container.append(prestasi_buttonAdd);
			container.append(' | ');
            container.append(prestasi_searchField);
            toolbar.append(container);
        },
        rendergridrows : function(){
            return prestasi_adapter.records;
        },
        columns : [
            { text : 'Id', dataField : 'prestasi_id', hidden : true },
            { text : 'Kompetisi', dataField : 'lomba_judul' },
            { text : 'Sekolah', dataField : 'prestasi_sekolah_nama' },
            { text : 'Juara', dataField : 'juara_nama' },
            { text : 'Skor', dataField : 'prestasi_skor' },
            { text : 'Tanggal', dataField : 'prestasi_tanggal' },
			{ text : '&nbsp;', width: 30, cellsrenderer : function(row){
					var record = prestasi_grid.jqxGrid('getrowdata', row);
					var id = record.prestasi_id;
					return '<img src="assets/images/icons/edit.png" onClick="prestasi_edit(event, ' + id + ')" title="Ubah Data" style="margin:2px 7px 2px 7px;"/>';
				}
			},
			{ text : '&nbsp;', width: 30, cellsrenderer : function(row){
					var record = prestasi_grid.jqxGrid('getrowdata', row);
					var id = record.prestasi_id;
					return '<img src="assets/images/icons/delete.png" onClick="prestasi_delete(event, ' + id + ')" title="Hapus Data" style="margin:2px 7px 2px 7px;"/>';
				}
			}
        ]
    });
/* Grid Detail prestasi */
	var prestasi_det_grid = $("#prestasi_det_grid");
	prestasi_det_buttonAdd = $("<button style='margin-left: 5px;' id='prestasi_det_buttonAdd' style='float:left;'><img src='assets/images/icons/add.png'> Tambah Siswa</button>");
    prestasi_det_buttonAdd.jqxButton({ width : 120 });
    prestasi_det_buttonAdd.bind('click', function(e){
		e.preventDefault();
		var selectedindex = prestasi_det_searchField.jqxComboBox('getSelectedIndex');
		if(selectedindex >= 0){
			var records = prestasi_det_siswaAdapter.records[selectedindex];
			var total = prestasi_det_grid.jqxGrid('getdatainformation').rowscount;
			var inlist = 0;
			for(var i=0; i < total; i++){
				console.log(prestasi_det_grid.jqxGrid('getrowdata',i).det_prestasi_siswa_id);
				if(prestasi_det_grid.jqxGrid('getrowdata',i).det_prestasi_siswa_id == records.siswa_nis){
					inlist = 1;
					break;
				}
			}
			if(inlist == 0){
				var rowid = prestasi_det_grid.jqxGrid('getdatainformation').rowscount + 1;
				var row = {};
				row['det_prestasi_id']=0;
				row['det_prestasi_siswa_id']=records.siswa_nis;
				row['det_prestasi_siswa_nama']=records.siswa_nama;
				row['det_prestasi_siswa_alamat']=records.siswa_alamat;
				row['det_prestasi_siswa_kelas']=records.siswa_kelas;
				row['det_prestasi_siswa_tgllahir']=records.siswa_tgllahir;
				var commit = prestasi_det_grid.jqxGrid('addrow',rowid, row, 'top');
				prestasi_det_searchField.jqxComboBox('clearSelection');
			}else if(inlist == 1){
				alert('Siswa telah masuk dalam data kelompok.');
			}
		}
	});
	
	prestasi_det_siswaAdapter = new $.jqx.dataAdapter({
		datatype: "json",
		root : 'results',
		data : {search_text : ''},
		datafields: [
			{ name: 'siswa_nis' },
			{ name: 'siswa_nama' },
			{ name: 'siswa_alamat' },
			{ name: 'siswa_kelas' },
			{ name: 'siswa_tgllahir' }
		],
		url: "index.php/c_prestasi/get_list_siswa"
	});
	prestasi_det_searchField = $("<div id='prestasi_det_prestasi_det_searchField' style='float:left;'></div>");
	prestasi_det_searchField.jqxComboBox({
        width: 300,
        height: 25,
        displayMember: "siswa_nama",
        valueMember: "siswa_nis",
        source: prestasi_det_siswaAdapter,
		autoDropDownHeight : true,
		minLength : 3,
		remoteAutoComplete : true,
		search: function (searchString) {
			var source = prestasi_det_siswaAdapter._source;
			source['data']['search_text'] = searchString;
			prestasi_det_siswaAdapter.dataBind();
		}
    });
	
    prestasi_det_source={
        url : 'index.php/c_prestasi/get_list_detail',
        datatype : 'json',
        root : 'results',
		data : {prestasi_id : 0},
        datafields : [
            { name : 'det_prestasi_id' },
            { name : 'det_prestasi_siswa_id' },
            { name : 'det_prestasi_siswa_nama'},
            { name : 'det_prestasi_siswa_kelas'},
            { name : 'det_prestasi_siswa_alamat'},
            { name : 'det_prestasi_siswa_tgllahir'}
        ],
        beforeprocessing : function(data){
            prestasi_det_source.totalrecords = data[0].total;
        },
		addrow: function (rowid, rowdata, position, commit) {
			commit(true);
		},
		deleterow: function (rowid, commit) {
			commit(true);
		}
    }
    prestasi_det_adapter = new $.jqx.dataAdapter(prestasi_det_source);
   
    prestasi_det_grid.jqxGrid({
        source : prestasi_det_adapter,
        width : '100%',
        theme : global_theme,
        pagesize : 15,
        pagesizeoptions : [15],
        sortable : true,
		pageable: true,
        filterable : true,
        columnsresize : true,
        autoheight : true,
        virtualmode : true,
        showtoolbar: true,
		editable: true,
		selectionmode: 'singlerow',
		editmode: 'selectedrow',
        rendertoolbar: function (toolbar) {
            var me = this;
            var container = $("<div style='margin: 5px;'></div>");
			container.append(prestasi_det_searchField);
			container.append(' | ');
            container.append(prestasi_det_buttonAdd);
            toolbar.append(container);
        },
        rendergridrows : function(){
            return prestasi_det_adapter.records;
        },
        columns : [
            { text : 'Id', dataField : 'det_prestasi_id', hidden : true},
            { text : 'NIS', dataField : 'det_prestasi_siswa_id'} ,
            { text : 'Nama', dataField : 'det_prestasi_siswa_nama'} ,
            { text : 'Kelas', dataField : 'det_prestasi_siswa_kelas'} ,
            { text : 'Alamat', dataField : 'det_prestasi_siswa_alamat'} ,
			{ text : '&nbsp;', width: 30, editable: false, cellsrenderer : function(row){
					var record = prestasi_det_grid.jqxGrid('getrowdata', row);
					var id = record.prestasi_det_id;
					return '<img src="assets/images/icons/delete.png" id="prestasi_detdelbtn_' + id + '" onClick="prestasi_det_delete(event, ' + id + ')" title="Hapus Data" style="margin:2px 7px 2px 7px;"/>';
				}
			}
        ]
    });
/* Function Declaration */
    function prestasi_reset_form(){
        prestasi_expander.jqxExpander('collapse');
		prestasi_det_grid.jqxGrid('clear');
		$("#prestasi_id").val('');
		<?php
			if($_SESSION[SESSION_SCHOOLID] != 0){
				echo "$('#prestasi_sekolah_nama').val('". $_SESSION[SESSION_SCHOOLNAME] ."');";
				echo "$('#prestasi_sekolah_id').val('". $_SESSION[SESSION_SCHOOLID] ."');";
				echo "$('#prestasi_sekolah_nama').prop('disabled', true);";
			}
		?>
		$("#prestasi_lomba_id").jqxComboBox('val', '');
		$("#prestasi_juara_id").jqxComboBox('val', '');
		
		prestasi_buttonAdd.jqxButton({ disabled : false});
    }
    function prestasi_save_form(e){
        e.preventDefault();
        var params = new Object();
        params.prestasi_id=$('#prestasi_id').val();
        params.prestasi_sekolah_id=$('#prestasi_sekolah_id').val();
        params.form_data=$('#prestasi_form').serializeObject();
        params.form_data.prestasi_lomba_id = $("#prestasi_lomba_id").jqxComboBox('val');

		params.form_data.prestasi_juara_id=$("#prestasi_juara_id").jqxComboBox('val');
		params.form_data.prestasi_tanggal=$("#prestasi_tanggal").jqxDateTimeInput('val');
		params.detail=prestasi_det_source.records;
        params=JSON.stringify(params);
        $.ajax({
            url : 'c_prestasi/save',
            method : 'post',
            data : {params:params},
            success : function(response){
                var res = $.parseJSON(response);
                prestasi_grid.jqxGrid('updatebounddata');
                $.global_show_notif(MSAVE_SUCCESS,'success');
                prestasi_reset.click();
            }
        });
    }
	function fprestasi_edit(e, prestasi_id){
		var rowindex = prestasi_grid.jqxGrid('getselectedrowindex');
		var data_record = prestasi_grid.jqxGrid('getrowdata', rowindex);
		$("#prestasi_form").unserializeObject(data_record);
		
		$("#prestasi_lomba_id").jqxComboBox('val', data_record.prestasi_lomba_id);
		$("#prestasi_juara_id").jqxComboBox().find('input').val(data_record.juara_nama);
		$("#prestasi_tanggal").jqxDateTimeInput('val', data_record.prestasi_tanggal);
		$("#prestasi_sekolah_nama").val(data_record.prestasi_sekolah_nama);
		
		prestasi_expander.jqxExpander('expand');
		prestasi_det_source['data']['prestasi_id'] = prestasi_id;
		prestasi_det_adapter.dataBind();
		
		prestasi_buttonAdd.jqxButton({ disabled : true});
	}
	prestasi_edit = fprestasi_edit;
	function fprestasi_delete(e, prestasi_id){
		var rowindex = prestasi_grid.jqxGrid('getselectedrowindex');
		var data_record = prestasi_grid.jqxGrid('getrowdata', rowindex);
		$.global_show_confirm('Peringatan',MCONFIRM_DELETE_MASTER);
		$("#confirm_window_ok").click(function(){
			var process = $.global_show_processing();
			$.ajax({
				url : 'c_prestasi/delete',
				method : 'post',
				data : {prestasi_id:prestasi_id},
				success : function(response){
					process.hide();
					var res = $.parseJSON(response);
					prestasi_grid.jqxGrid('updatebounddata');
					$.global_show_notif(MSAVE_SUCCESS,'success');
					prestasi_reset.click();
				}
			});
		});
	}
	prestasi_delete = fprestasi_delete;
	prestasi_searchField.on('keydown', function(e){
		if(e.keyCode == 13){
			prestasi_source['data']['search_text'] = $(this).val();
			prestasi_grid.jqxGrid('gotopage',0);
			prestasi_grid.jqxGrid('updatebounddata');
		}
	});
	
	prestasi_det_delete = function(){
		var selectedrowindex = $("#prestasi_det_grid").jqxGrid('getselectedrowindex');
		var rowscount = $("#prestasi_det_grid").jqxGrid('getdatainformation').rowscount;
		if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
			var id = $("#prestasi_det_grid").jqxGrid('getrowid', selectedrowindex);
			var commit = $("#prestasi_det_grid").jqxGrid('deleterow', id);
		}
	}
	
	prestasi_reset_form();
});
</script>
<div>
    <div id="prestasi_expander" style="padding-bottom : 10px;">
        <div>Form Tambah/Ubah Data Prestasi</div>
        <div>
            <form class="form-horizontal" id="prestasi_form" style="padding:10px;overflow:hidden;">
                <input type="hidden" id="prestasi_id" name="prestasi_id">
                <input type="hidden" id="prestasi_sekolah_id" name="prestasi_sekolah_id">
                <div class="form-group">
                    <label class="col-sm-2 control-label">Kompetisi</label>
                    <div class="col-sm-4"><div id="prestasi_lomba_id"></div></div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">Sekolah</label>
                    <div class="col-sm-4"><input type="text" class="inputfield" name="prestasi_sekolah_nama" id="prestasi_sekolah_nama"></div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">Tanggal</label>
                    <div class="col-sm-4"><div id="prestasi_tanggal"></div></div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">Juara</label>
                    <div class="col-sm-4"><div id="prestasi_juara_id"></div></div>
                </div>
				<div id="prestasi_det_grid"></div><br/>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-4 text-center">
                        <button type="button" id="prestasi_save">Simpan</button>
                        <button type="reset" id="prestasi_reset">Batal</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <div id="prestasi_grid"></div>
</div>